import login from '@/api/login.js';
import searchApi from '@/api/search.js';
import request from '@/utils/request/index.js'

export default {
	
	testTagName(newTagName){
	    let tagRegex = /^[\u4E00-\u9FA5A-Za-z0-9]*$/;
	    return tagRegex.test(newTagName);
	},
	getFrontMenu(){
		return request.request({
			url: "/h5/frontindexmenu/getList",
			method: 'get',
			data:{}
		})
	},
	getFindMenu(type){
		return request.request({
			url: "/h5/frontindexmenu/getListByType/" + type,
			method: 'get',
			data:{}
		})
	},
	saveFootPrint(userId,timeIn,second,url,title){
		return request.request({
			url: "/h5/nocuserfootprint/saveforapplet",
			method: 'post',
			data:{
				userId: userId,
				accessTimes: timeIn,
				residenceTime: second,
				pageAddres: url,
				pageTitle: title,
			}
		})
	},
	
	updUserInfo(id,type){
		return request.request({
			url: "/h5/nocuser/updUserInfo",
			method: 'post',
			data:{
				id: id,
				lastLoginTimeUFlag: 3,
				type: type
			}
		})
	},
	/**
	 * 保存搜索历史
	 */
	saveSearchKey({keyword,type=1}){
		return request.request({
			url: "/h5/searchkey/save",
			method: 'post',
			data: {
				keyword: keyword,
				type:type
			},
		})
	},
	/**
	 * 获取小程序openid
	 * @param code
	 * @returns {*}
	 */
	getOpenId(code){
		return request.request({
			url:'/h5/weixinpay/getMiniOpenId',
			method:'get',
			data:{
				code:code,
			},
		})
	},
	/**
	 * 文字内容安全验证
	 */
	async msgSecCheck(msg,scene,openid){
		return request.request({
			url: '/h5/weixinpay/msgSecCheck',
			method: 'post',
			data: {
				"content": msg,
				"version": 2,
				"scene": scene,
				"openid": openid,
			}
		})
	},

	/** 获取费率，计算可提现金额
	 * @param {Object} userId
	 * @param {Object} withdrawMoney
	 * @param {Object} openId
	 */
	preWithdrawal(userId,withdrawMoney,openId){
		return request.request({
			url: '/h5/weixinpay/preWithdrawal',
			method: 'post',
			data:{
				userId: userId,
				total_fee: withdrawMoney,
				unit: 'yuan',
				openId: openId
			}
		})
	},
	/**提现
	 * @param {Object} userId
	 * @param {Object} preWithdrawMoney
	 * @param {Object} serviceCharge
	 * @param {Object} openId
	 * @param {Object} verificationCode
	 */
	withdrawal(userId,preWithdrawMoney,serviceCharge,openId,verificationCode){
		return request.request({
			url: '/h5/weixinpay/withdrawal',
			method: 'post',
			data:{
				userId: userId,
				total_fee: preWithdrawMoney,
				serviceCharge: serviceCharge,
				unit: "yuan",//充值金额单位
				openId: openId,
				verificationCode: verificationCode,
			}
		})
	},
	/**
	 * 购买会员需求
	 */
	topUp(userInfo, money){ 
		return request.request({
			url: '/h5/weixinpay/topUp',
			method:'post',
			data:{
				userId: userInfo.id, //诺展用户id
				total_fee: money,//充值金额
				openId: userInfo.openId,//openid
				unit: "yuan",//充值金额单位,
				tradeType: "JSAPI",//支付方式为微信内置浏览器
			}
		})
	},
	//获取样册
	/**
	 * @param {Object} id
	 */
	getSampleBook(id){
		return request.request({
			url: '/h5/nocsamplebook/info/' + id,
			method : 'post',
		})
	},
	/**
	 * 购买会员需求
	 */
	buyVip(userInfo, money,userMemberConfig){
		return request.request({
			url: '/h5/weixinpay/buyVip',
			method:'post',
			data:{
				userId: userInfo.id, //诺展用户id
				total_fee: money,//充值金额
				openId: userInfo.openId,//openid
				unit: "yuan",//充值金额单位,
				tradeType: "JSAPI",//支付方式为微信内置浏览器
				chargeType : "demand",//充值类型 ： 需求充值
				ifOnce: userMemberConfig.ifOnce,
				demandNumber: userMemberConfig.demandNumber
			}
		})
	},
	/**
	 * 获取当前用户会员需求使用明细
	 */
	getMemberDemandDetail(){
		return request.request({
			url: '/h5/memberdemanddetail/getList',
			method: 'post',
			data:{}
		})
	},

	/**
	 * 获取个人账单
	 * @param {Object} tagName
	 */
	getUserBills(queryMap){
		return request.request({
			url: '/noc/noctranslog/userBill',
			method: 'post',
			data: queryMap
		})
	},
	
	/**
	 * 输入获取标签列表
	 */
	getTagList(tagName){
		return request.request({
			url: '/h5/noctag/list',
			methods: 'post',
			data:{
				tagName: tagName,
				page : 1,
				limit: 20,
			}
		})
	},
	/**
	 * 获取用户当日拨打次数
	 */
	getTodayCallCount(userId){
		return request.request({
			url: '/h5/nocyxbrowse/countByTypeToday?userId=' + userId + '&type=6',
			method: 'get',
			data:{}
		})
	},
	/**
	 * 拨打电话限制，如果未超限才进行拨打电话
	 * @param userId
	 */
	async callPhoneLimit(userId,phone,userType,userState){
	   let browseCount = 0
		await this.getTodayCallCount(userId).then(res =>{
			browseCount = res.data.browseCount
		})
	   return await this.getConfig().then(res=>{
			let limit;
			let warning;
			res.data.list.forEach((value,index,array)=>{
				if(userType == 1 && userState == 1) {
					if (value.paramKey.includes("callphone_limit_num_supplier")) {
						limit = value.paramValue;
					}
				}else{
					if (value.paramKey.includes("callphone_limit_num_buyer")) {
						limit = value.paramValue;
					}

				}
				if(value.paramKey.includes("callphone_limit_warning")){
					warning = value.paramValue;
				}
			})
			if (limit && limit!='0' && browseCount >= limit){
				uni.showModal({
					title: "提示",
					content: warning,
					showCancel:false,
					success: function (res) {
						if (res.confirm) {
							console.log('用户点击确定');
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
				return false;
			}
			this.callUp(phone)
			return true;
		})
	
	},

	/**
	 * 拨打电话
	 */
	async callPhone(type, userId, businessId, businessType, phone,phoneIndex,userType,userState) {
		const result = await this.getUserLoginFlag()
		if (result) {
			return
		}
		let flag = await this.callPhoneLimit(userId,phone,userType,userState);
		if(flag){
			this.recordBrowse(type, userId, businessId, businessType,phone)
		}
		
		// this.callUp(phone)
	},
	/**
	 * 获取动态列表
	 */
	getNews({page = 1, limit = 10, userId = '', searchKey = '', newsPx = '', tagType = 1, tagId = 0}){
		return request.request({
			url:'/h5/nocnews/list',
			method:'post',
			data:{
				page: page,
				limit: limit,
				userId: userId,
				searchKey: searchKey,
				newsPx: newsPx,
				tagType: tagType,
				tagId: tagId,
			},

		})

	},
	
	//进入个人主页
	enterPersonal(userId){
		uni.navigateTo({
			url: '/pages/person/anchorHomepage?userId='+ userId
		})
	    // window.location.href = '/h5/anchorHomepage.html?userId=' + userId;
	},
	
	//进入展厅页面
	enterComp(userId){
		uni.navigateTo({
			url:'/pages/product/showroom/showroom?userId='+ userId
		})
	    // window.location.href = '/h5/cloudcomp.html?userId=' + userId;
	},
	
	//根据用户类型进入个人主页或者展厅页面
	enterPersonalByType(user){
	    if (user.type == 1 && user.state == 1) {
	        this.enterComp(user.id)
	    } else {
	        this.enterPersonal(user.id)
	    }
	},

	/**
	 * 判断用户是否登陆
	 * @param currentRes
	 * @returns {Promise<boolean>}
	 */
	async judgeLogin(currentRes){
	    if (!currentRes) {
	        currentRes = await this.currentUserAxios()
	    }
	    if (currentRes.data.code === 0) {
	        const currentUser = currentRes.data.session_user_h5
	        return this.toRegistered(currentUser.type)
	    }
	},
	/**
	 * 判断用户是否绑定手机号,因为绑定手机号后该页面当前用户信息不更新,所以每次都进行查询
	 * @param currentRes
	 * @returns {Promise<boolean>}
	 */
	async judgeIfPhone(currentRes){
	    if (!currentRes) {
	        currentRes = await this.currentUserAxios()
	    }
	    //首先判断用户是否登陆
	    let res = await this.judgeLogin(currentRes)
	    if (!res) {
	        return false
	    }
	    if (currentRes.data.code === 0) {
	        const currentUser = currentRes.data.session_user_h5
	        if (!(currentUser.phone.indexOf('yk') != -1)) {
	            return true;
	        } else {
	            //绑定手机号弹窗
	            // bindPhonePop()
	            return false;
	        }
	    }
	},
	
	//取消收藏
	cancelCollect(collectionId, userId, businessId, type){
		return request.request({
			url: '/h5/nocyxcollect/cancelCollection',
			method: 'post',
			data: {
				collectionId : collectionId,
				userId: userId,
				businessId: businessId,
				type: type,
			}
		})
	},

    /**
     * 获取当前用户
     * @returns {*}
     */
    async currentUserAxios() {
        let result = '';
        await login.getCurrentUser().then(data => {
            result = data;
        });
        return result;
    },

	/**
	 * 微信网页动态修改title
	 * @param title
	 */
	setDocumentTitle(title) {
		document.title = title;
		var i = document.createElement('iframe');
		i.src = '../favicon.ico';
		i.style.display = 'none';
		i.onload = function () {
			setTimeout(function () {
				i.remove();
			}, 9)
		}
		document.body.appendChild(i);
	},
	
	
	/**
	 * 判断用户信息是否完整
	 * @param currentRes
	 * @returns {Promise<boolean>}
	 */
	async judgeNocuserUserInfo(currentRes){
	    if (!currentRes) {
	        currentRes = await this.currentUserAxios()
	    }
	    //首先判断用户是否登陆
	    let res = await this.judgeLogin(currentRes)
	    if (!res) {
	        return false
	    }
	    if (currentRes.data.code === 0) {
	        const currentUser = currentRes.data.session_user_h5
	        if (currentUser.phone && currentUser.userName && currentUser.company && currentUser.position && currentUser.nickName) {
	            return true;
	        } else {
	            //完善信息弹窗
	            // completeInfoPop()
	            return false;
	        }
	    }
	},



    /**
     * 判断用户是否登录，不登录的状态显示“立即登录”弹窗
     * @returns {boolean}
     */
    async getUserLoginFlag() {
        let res = await this.currentUserAxios();
        //判断是否绑定手机号
        if (res.data.session_user_h5.phone && res.data.session_user_h5.phone.indexOf('yk') == -1) {
            return false;
        } else {
            //立即登录弹窗
            return true;
        }
        //判断是不是游客
        if (res.data.session_user_h5 &&
            (res.data.session_user_h5.type === 1 || res.data.session_user_h5.type === 2)) {
            return false;
        } else {
            return true;
        }
    },
	
	async judgeIfPhoneNoJudgeLog (currentRes){
	    if (!currentRes) {
	        currentRes = await login.getCurrentUser()
	    }
	
	    if (currentRes.data.code === 0) {
	        const currentUser = currentRes.data.session_user_h5
	        if (!(currentUser && currentUser.phone && currentUser.phone.indexOf('yk') != -1)) {
	            return true;
	        } else {
	            return false;
	        }
	    }
	},
	

    /**
     * 滑动校验，校验成功后发送验证码
     * @param data
     */
    slideCheck(phone) {
        if (!validPhone(phone)) {
            uni.showToast({
                "title": "请检查手机号",
                "icon": "none",
            });
            return false
        }
        login.getCheckCode(
            {
                phone: data.phone
            }
        ).then(res => {
            if (res.data.code == 0 && res.data.CaptchaCode == 1) {
                uni.showToast({
                    "title": "发送验证码成功",
                    "icon": "none",
                });
            } else {
                uni.showToast({
                    "title": "验证失败",
                    "icon": "none",
                });
            }
        });
    },

    /**
     * 校验手机号
     * @param phone
     * @returns {boolean}
     */
    validPhone(phone) {
        if (!phone) {
            return false;
        }
        let telStr = /^[1]([3-9])[0-9]{9}$/
        let test = telStr.test(phone)
        if (!test) {
            return false
        }
        return true
    },

	/**
	 * 首页产品价格格式修改
	 * @param {Object} price
	 */
	handlePrice(price){
	    let res = 0;
	    if (price >= 10000){
	        res = (price / 10000);
	        res += '万';
	    }else{
	        return  price;
	    }
	    return res;
	},

    /**
     * 跳转到搜索页面
     * @param index
     * @param searchKey
     * @param ifRecommend
     * @param isNewProduct
     */
    toSearchPage({index, searchKey = '', ifRecommend = 1,isNewProduct}) {
		//供应商页面
		//pages/product/recommend/recommend
		//商品
		//pages/product/recommend/recommend
		//新品
		//pages/product/concentration/concentration

        uni.redirectTo({
            url: '/pages/product/concentration/concentration?index=' + index + '&searchKey=' + encodeURIComponent(searchKey) + '&ifRecommend=' + ifRecommend + '&isNewProduct=' + isNewProduct
        })
    },

    /**
     * 保存搜索关键字
     * @param keyword
     * @param type
     */
 //    saveSearchKey({keyword,type=1}) {
 //        searchApi.saveSearchKey({
 //            keyword: keyword,
 //            type:type
 //        });
	// },

	/**
	 * 需求时间显示格式修改
	 * @param {Object} setDateTimeStamp
	 */
	transtionTime(setDateTimeStamp){
	    var result = setDateTimeStamp;
	    var minute = 1000 * 60;
	    var hour = minute * 60;
	    var day = hour * 24;
	    var month = day * 30;
	    var years = month * 12;
	    // 格式化日期
	    var dateTimeStamp = new Date(setDateTimeStamp.replace(/\-/g, '/'));
		console.log(dateTimeStamp.getMonth());
	    // 获取当前时间
	    var now = new Date().getTime();
	    // 求时间差
	    var diffValue = now - dateTimeStamp;
	    // 结束日期不能小于开始日期，返回原值
	    if (diffValue < 0) {
	        console.log("结束日期不能小于开始日期！");
	        return setDateTimeStamp;
	    }
	    var yearsC = diffValue / years;
	    var monthC = diffValue / month;
	    var weekC = diffValue / (7 * day);
	    var dayC = diffValue / day;
	    var hourC = diffValue / hour;
	    var minC = diffValue / minute;
	    var yearDiff = new Date(now).getFullYear() - dateTimeStamp.getFullYear();
	    var monthDiff = new Date(now).getMonth() - dateTimeStamp.getMonth();
	    var dayDiff = new Date(now).getDate() - dateTimeStamp.getDate();
	    // 同年同月不同天的情况
	    if (yearDiff == 0 && monthDiff == 0) {
	        switch (dayDiff) {
	            case 0:
	                if (hourC >= 1) {
	                    result = parseInt(hourC) + "小时前";
	                } else if (minC >= 1) {
	                    result = parseInt(minC) + "分钟前";
	                } else {
	                    result = "1分钟前";
	                }
	                break;
	            case 1:
	                result = "昨天";
	                break;
	            case 2:
	            case 3:
	            case 4:
	            case 5:
	            case 6:
	            case 7:
	                result = dayDiff + "天前";
	                break;
	            default:
	                if (weekC >= 1) {
	                    result = parseInt(weekC) + "周前";
	                }
	        }
	    } else {
	        if (yearsC >= 1) {
	            result = parseInt(yearsC) + "年前";
	        } else if (monthC >= 1) {
	            result = parseInt(monthC) + "月前";
	        } else {
	            // 跨月且不满30天的情况，intercalaryMonth代表每月天数
	            // 平年2月28天，闰年29天，4、6、9、11月30天，其余31天，
	            // 用于计算跨月天数差
	            let intercalaryMonth = 0;
	            switch (dateTimeStamp.getMonth() + 1) {
	                case 4:
	                case 6:
	                case 9:
	                case 11:
	                    intercalaryMonth = 30;
	                    break;
	                case 2:
	                    intercalaryMonth = this.intercalary(dateTimeStamp.getFullYear());
	                    break;
	                default:
	                    intercalaryMonth = 31;
	            }
	            if ((intercalaryMonth + dayDiff) <= 7) {
	                result = (intercalaryMonth + dayDiff) + "天前";
	            } else {
	                result = parseInt(weekC) + "周前";
	            }
	        }
	    }
	    return result;
	},
	// 闰年平年2月天数计算
	intercalary(getYear){
	    let result = '';
	    if (getYear.toString().substring(2) == '00') {
	        if (getYear.toString().substring(0, 2) % 4 != 0) {
	            result = 28
	        } else {
	            result = 29;
	        }
	    } else {
	        if (getYear.toString().substring(2) % 4 != 0) {
	            result = 28;
	        } else {
	            result = 29;
	        }
	    }
	    return result;
	},
	/**
	 * 获取total_img
	 */
	async getTotalImg(){
	    const configRes =  await login.getSystemConfig();
	    let imgUrl = ''
	    if (configRes.data.code === 0) {
	        const configList = configRes.data.list
	        configList.forEach((value, index, array) => {
	            if (value.paramKey === 'total_img') {
	                imgUrl = value.paramValue
	            }
	        })
	    }
	    return imgUrl;
	},

	/**
	 * 获取参数配置
	 */
	getConfig() {
		return login.getSystemConfig();
	},

	groupQrCode(id){
		return request.request({
			url:'/h5/groupqrcode/getGroupQrCode/'+id,
			method:'get',
		})
	},
	// getActivityProByProId(productId){
	// 	return request.request({
	// 		url:'/h5/activityproduct/info/'+productId,
	// 		method:'get',
	// 	})
	// },
	/**
	 * 判断是否是游客登录,如果是游客登录提示客户进行登录或者注册
	 * @param userType
	 * @returns {boolean}
	 */
	toRegistered(userType){
	    if (userType == 3 || userType == undefined){
	        /*
				提示登录，跳转登录页面
			*/
			uni.redirectTo({
				url: '/pages/account/login/login'
			})
	        return false
	    } else {
	        return true
	    }
	},
	/**获取视频列表
	 * @param {Object} search
	 */
	getVideoList(search){
		return request.request({
			url: '/h5/nocvideo/list',
			method : 'post',
			data:{
				relatedType : 1 ,
				page: search.page,
				limit: search.limit,
				search: search.search,
				lastpage: search.lastpage,
				totalPage: search.totalPage,
				userId: search.userId,
				totalCount: search.totalCount,
				tagType: search.tagType,
				tagId: search.tagId,
			}
		})
	},
	/**获取动态列表
	 * @param {Object} search
	 */
	// getNews(search){
	// 	console.log(2);
	// 	return request.request({
	// 		url: '/h5/nocnews/list',
	// 		method : 'post',
	// 		data: search,
	// 	})
	// },
	/**视频时长格式整理
	 * @param {Object} value
	 */
	formatDurantion(value){
		let duration = '';
		value.videoDuration = value.videoDuration.slice(-8);
		if (value.videoDuration.length == 8) {
			let timeArray = value.videoDuration.split(':')
			if (timeArray[0] == '00') {
				timeArray[0] = ''
			} else if (timeArray[0].slice(0, 1) == '0') {
				timeArray[0] = timeArray[0].slice(1) + ':'
			} else {
				timeArray[0] = timeArray[0] + ':'
			}
			value.videoDuration = timeArray[0] + timeArray[1] + ':' + timeArray[2]
		}
		duration = value.videoDuration
		return duration;
	},
	/**获取被收藏量, types : 1.产品收藏  2.需求收藏 3.关注 4.点赞
	 * @param {Object} userId
	 * @param {Object} types
	 * @param {Object} productId
	 * @param {Object} demandId
	 */
	getCollectMineByType(userId, types, productId, demandId){
	    return request.request({
	    	url: '/h5/nocyxcollect/collectMineByType',
	    	method : 'post',
			data:{
				userId: userId,
				types: types,
				productId: productId || undefined,
				demandId: demandId || undefined,
			}
	    })
	},
	/**获取关注人和点赞  type： 3.关注人 4.点赞
	 * @param {Object} type
	 * @param {Object} userId
	 */
	getCollectionCountByTypeAxios(type, userId){
		return request.request({
			url: '/h5/nocyxcollect/countByType',
			method : 'post',
			data:{
				userId: userId,
				type: type,
			}
	    })
	},

	/**
	 * 获取被浏览量,1.产品浏览 2.需求浏览 3.展商主页 4.直播观看 5.在线沟通 6.电话沟通
	 * @param userId
	 * @param types
	 * @param productId
	 * @returns {*}
	 */
	getBrowseMineByType(userId, types, productId) {
		return request.request({
			url: '/h5/nocyxbrowse/browseMineCount',
			method : 'post',
			data:{
				userId: userId,
				types: types,
				productId: productId
			}
		})
	},
	/**
	 * 获取被浏览量,1.产品浏览 2.需求浏览 3.展商主页 4.直播观看 5.在线沟通 6.电话沟通
	 * @param userId
	 * @param types
	 * @returns {*}
	 */
	getBrowseMineByType2(userId, types) {
		return request.request({
			url: '/h5/nocyxbrowse/browseMineCount',
			method : 'post',
			data:{
				userId: userId,
				types: types,
			}
		})
	},
	/**
	 * 发送评论
	 * @param userId 用户id
	 * @param content 内容
	 * @param businessId 资讯/视频id
	 * @param type news-资讯,video-视频
	 * @returns {Promise<awaited RESULT>}
	 */
	async sendComment(userId, content, businessId, type){
		return request.request({
			url: '/h5/nocyxcomment/sendComment',
			method : 'post',
			data:{
				userId: userId,
				content:content,
				businessId:businessId,
				type: type,
			}
		})
	},
	/**
	 * 获取评论
	 * @param unFoldIndex 不折叠该行
	 * @param businessId 视频id
	 * @param userId 用户id
	 */
	getComment(businessId, userId, type){
		return request.request({
			url: '/h5/nocyxcomment/getComment?businessId=' + businessId + '&userId=' + userId + '&type=' + type,
			method : 'get',
		})
	},
	/**展商展厅页面关注，取消关注
	 * @param {Object} userId
	 * @param {Object} shoucangFlag
	 */
	subscriptionOrNot(userId,shoucangFlag){
		return request.request({
			url:'/h5/noccloudhome/shoucang',
			method:'post',
			data:{
				userId:userId,
				shoucangFlag:shoucangFlag,
			}
		})
	},

	/**
	 * 获取聊天会话
	 * @param groupId
	 * @returns {IDBRequest<IDBValidKey> | Promise<void>}
	 */
	getMsgGrop(groupId) {
		return request.request({
			url: '/h5/nocmsgcontent/getMsgGrop',
			method : 'put',
			data:{
				groupId: groupId
			}
		})
	},
	//获取分享页面参数配置
	getPageShareConfig(){
		return request.request({
			url:'/h5/pageshareconfig/getPageShareConfig',
			method:'get',
			data:{}
		})
	},


	/**
	 * 拨打电话
	 */
	callUp(phone) {
		uni.makePhoneCall({
			phoneNumber:phone,
			success:function(){
				console.log('拨打电话成功');
			},
			fail() {
				console.log('打电话失败了');
			}
		})
	},

	/**
	 * 记录方法,type为记录类型,businessId为产品\需求\nocUserID,businessType为1.产品ID2.需求ID3.用户ID
	 * @param type
	 * @param userId
	 * @param businessId
	 * @param businessType
	 */
	recordBrowse(type, userId, businessId, businessType,phone) {
		return request.request({
			url: '/h5/nocyxbrowse/save',
			method : 'put',
			data:{
				userId: userId,
				type: type,
				businessId: businessId,
				businessType: businessType,
				phoneNumber: phone
			}
		});
	},

	/**
	 * 上传图片
	 * @param tempFile
	 * @returns {*}
	 */
	uploadNewsImg(tempFile) {
		return request.request({
			url: '/sys/oss/upload',
			method: 'post',
			data: tempFile,
			header: {'Content-Type': 'multipart/form-data'}
		})
	},
	//购买需求会员和 需求条数
	/**
	 * @param {Object} userInfo
	 * @param {Object} rechargeMoney
	 * @param {Object} navigateUrl
	 */
	purchaseDemandService(userInfo, rechargeMoney, navigateUrl){
	    // if (isWeiXin()) {
	        //如果是微信内置浏览器
	        if (!(userInfo.id && userInfo.openId)) {

				uni.showModal({
					title: "",
					content: "没有获取微信授权,点击确定授权",
					showCancel:false,
					success: function (res) {
						var that = this
						if (res.confirm) {
							console.log('用户点击确定');
							if (navigateUrl) {
								that.getOpenId(navigateUrl).then(response =>{
									console.log("getOpenId");
									console.log(response);
								})
								// uni.navigateTo({
								// 	// url: '/components/webview/webview?url=' + encodeURIComponent('/h5/getOpenId?backUrl=' + navigateUrl)
								// 	url: '/h5/getOpenId?backUrl=' + navigateUrl
								// })

							    // window.location.href = '/h5/getOpenId?backUrl=' + navigateUrl
							} else {
							    // window.location.href = '/h5/getOpenId?backUrl=' + window.location.pathname + window.location.search
							}
							// layer.close(index)
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}.bind(this)
				});

	            return;
	        }
			this.recharge(userInfo,rechargeMoney).then(res => {
	            if (res.data.code == 0) {
	                WeixinJSBridge.invoke(
	                    'getBrandWCPayRequest', {
	                        "appId": res.data.map.appId,//公众号名称，由商户传入
	                        "timeStamp": res.data.map.timeStamp,//时间戳，自1970年以来的秒数
	                        "nonceStr": res.data.map.nonceStr, //随机串
	                        "package": res.data.map.package,
	                        "signType": res.data.map.signType,//微信签名方式
	                        "paySign": res.data.map.paySign //微信签名
	                    },
	                    function (res) {
	                        if (res.err_msg == "get_brand_wcpay_request:ok") {
	                            // 使用以上方式判断前端返回,微信团队郑重提示：
	                            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
	                            if (navigateUrl) {
									uni.redirectTo({
										url:navigateUrl
									})
	                            }
	                        } else if (res.err_msg == "get_brand_wcpay_request:cancel" || res.err_msg == "get_brand_wcpay_request:fail") {
	                            //用户遇到错误或者主动取消,关闭弹窗
								uni.showToast({
									title: '若遇到问题，请点击页面下方【客服】咨询',
									duration:3000,
									success() {
										uni.redirectTo({
											url:navigateUrl
										})
									}
								})

	                        } else {
								uni.showModal({
									title: "",
									content: "支付遇到错误,如已付款请联系管理员",
									showCancel:false,
									success: function (res) {
										if (res.confirm) {
											console.log('用户点击确定');
											if (navigateUrl) {
												uni.redirectTo({
													url:navigateUrl
												})
											}
										} else if (res.cancel) {
											console.log('用户点击取消');
										}
									}
								});
	                        }
	                    });
	            } else {
	                //支付错误,提示用户
					uni.showModal({
						title: "",
						content: res.data.msg,
						showCancel:false,
						success: function (res) { 
							if (res.confirm) {
								console.log('用户点击确定');
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
	            }
	
	        })
	    // } 
	// 	else {
	//         //如果是外部浏览器
	//         axios.post("/h5/weixinpay/recharge", {
	//             userId: userInfo.id,
	//             total_fee: rechargeMoney,
	//             unit: "yuan",//充值金额单位,
	//             tradeType: "MWEB",//支付方式为微信内置浏览器
	//             chargeType : "demand",//充值类型 ：需求充值
	//         }).then(res => {
	//             if (res.data.code === 0) {
	//                 //通过mweb_url调起微信支付中间页
	//                 const mwebURL = res.data.map.mweb_url;
	//                 if (mwebURL) {
	//                     window.location.href = mwebURL;
	//                     layer.open({
	//                         title: '是否支付'
	//                         , content: "请确认是否支付成功"
	//                         , btn: ['已支付完成', '支付遇到问题,请重新支付']
	//                         , yes(index) {
	//                             queryOrderStatus(res.data.map.tradeNo, navigateUrl)
	//                         }
	//                         , no(index) {
	
	//                         }
	//                     });
	//                 } else {
	//                     layer.open({
	//                         content: '支付错误,请联系管理员'
	//                         , btn: '确定'
	//                         , yes(index) {
	//                             layer.close(index)
	//                         }
	//                     });
	//                 }
	
	//             } else {
	//                 layer.open({
	//                     content: res.data.msg
	//                     , btn: '确定'
	//                     , yes(index) {
	//                         layer.close(index)
	//                     }
	//                 });
	//             }
	
	//         })
	//     }
	},
	recharge(userInfo, rechargeMoney){
		return request.request({
			url: '/h5/weixinpay/recharge',
			method:'post',
			data:{
				userId: userInfo.id, //诺展用户id
				total_fee: rechargeMoney,//充值金额
				openId: userInfo.openId,//openid
				unit: "yuan",//充值金额单位,
				tradeType: "JSAPI",//支付方式为微信内置浏览器
				chargeType : "demand",//充值类型 ： 需求充值
			}
		})
	},
	//展会门票弹窗
	qrCode(memberId){
		let ticket = ''
		this.getMemberTicket(memberId).then(res =>{
	        if (Number(res.data.ticket.spectatorType)) {
	            res.data.ticket.spectatorType = '预登记观众'
	        } else {
	            res.data.ticket.spectatorType = '专业观众'
	        }
	
	        ticket =  res.data.ticket
	  
			let alert_ticket = `
					<div style="display: flex;align-items: center;flex-direction: column;z-index:99999">
						<div style="width: 8rem;height: auto;background-color: #0686a3;border-radius:20px;display: flex;flex-direction: column;justify-content: center;align-items:center">
							<div style="margin-top:0.5rem;margin-bottom:0.5rem;width: 5rem;background-color: #0686a3;display: flex;justify-content: center">
								<span style="color: white;font-size: 16px;font-weight: bold">${ticket.exhibitionName}</span>
							</div>
		
							<div style="background-image:url('/statics/js/modules/h5/img/qrcode_background.png');background-size:100% 100%;width: 6.5rem;;border-radius:16px;display: flex;flex-direction: column;align-items:center">
								<span style="margin-top:0.5rem;color:#0686a3;font-size: 14px;font-weight: 600">${ticket.spectatorType}·电子门票</span>
								<div style="margin-top:0.3rem;margin-bottom:0.3rem;width:5rem;border-top:1px dashed #0686a3;height: 1px;overflow:hidden"></div>
								<img style="width:6rem;" src="/h5/nocpreticket/getQrcode/${ticket.ticketCode}"/>
								<span style="margin-top:0.3rem;color:#0686a3;font-size: 14px;font-weight: 600">${ticket.company}</span>
								<span style="margin-bottom:0.2rem;color:#0686a3;font-size: 14px;font-weight: 600">${ticket.nickName}</span>
							</div>
							<div style="margin-top:0.2rem;width: 6.5rem;height: 1.5rem;background-color: #0686a3;display: flex;justify-content: center">
								<span style="color: white;font-size: 12px;">感谢您参观${ticket.exhibitionName},凭身份证或此二维码至展会现场入口处扫码入场!</span>
							</div>
						</div>
						<div style="width: 100%;display: flex;justify-content: center;margin-top: 0.5rem">
							<img onclick="layer.closeAll()" style="width: 1rem;height: 1rem" src="/statics/js/modules/h5/img/layerCloseBtn.png"/>
						</div>
					</div>
					`
			let alert_warn = `
					<div style="display: flex;align-items: center;flex-direction: column;z-index:99999">
						<div style="width: 8rem;height: auto;background-color: #0686a3;border-radius:20px;display: flex;flex-direction: column;justify-content: center;align-items:center">
							<div style="margin-top:0.5rem;margin-bottom:0.5rem;width: 5rem;background-color: #0686a3;display: flex;justify-content: center">
								<span style="color: white;font-size: 16px;font-weight: bold">${ticket.exhibitionName}</span>
							</div>
		
							<div style="background-image:url('/statics/js/modules/h5/img/qrcode_background.png');background-size:100% 100%;width: 6.5rem;height:9rem;border-radius:16px;display: flex;flex-direction: column;align-items:center">
								
								<div style="margin-top:0.3rem;color:#0b83a0;font-size: 20px;font-weight: 600;margin-top: 4rem;">
									<img  style="width: 0.5rem;height: 0.5rem" src="/statics/js/modules/h5/img/icon223.png"/>
									<span >您已报名成功</span>
								</div>
									
								<span style="margin-bottom:0.2rem;font-size: 10px;margin-top: 0.2rem;">注：开展期间将自动生成二维码</span>
							</div>
							<div style="margin-top:0.5rem;width: 6.5rem;height: 1.5rem;background-color: #0686a3;display: flex;justify-content: center">
								<span style="color: white;font-size: 12px;">感谢您参观${ticket.exhibitionName},凭身份证或此二维码至展会现场入口处扫码入场!</span>
							</div>
						</div>
						<div style="width: 100%;display: flex;justify-content: center;margin-top: 0.5rem">
							<img onclick="layer.closeAll()" style="width: 1rem;height: 1rem" src="/statics/js/modules/h5/img/layerCloseBtn.png"/>
						</div>
					</div>
					`;
			let ifBefore = (new Date(ticket.validStartTime.replaceAll('-','/'))).getTime() > new Date().getTime();
			uni.showModal({
				title: "",
				content: "<view v-html=" + ifBefore?alert_warn:alert_ticket + "></view>",
				content: "<view v-html=" + alert_warn + "></view>",
				showCancel:false,
				success: function (res) {
					if (res.confirm) {
						console.log('用户点击确定');
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
			// layer.open({
			// 	style: "background-color: transparent;",
			// 	content: ifBefore?alert_warn:alert_ticket
			// 	, shadeClose: false,
			// 	scrollbar: false,
			// 	success: function (layero, index) {
			// 		//该层弹出后在本地保存一个弹窗缓存标识
			// 		localStorage.setItem("layerPop", 1);
			// 	},
			// 	end: function () {
			// 		localStorage.setItem("layerPop", 0);
			// 	}
			// });
		})
	},
	getMemberTicket(memberId){
		return request.request({
			url:'/h5/nocpreticket/getInfoByMemberId/' + memberId,
			method: 'get',
			data:{},
		})
	},

	getDateOfString(time){
		if (time) {
			return new Date(time).getFullYear() + '-' + new Date(time).getMonth() + '-' + new Date(time).getDate()
		} else {
			return new Date().getFullYear() + '-' + new Date().getMonth() + '-' + new Date().getDate()
		}
	},
	updLogUserLogin(currentUser){
		if (currentUser.type != 3 && (this.getDateOfString(currentUser.lastLoginTime) != this.getDateOfString() || !currentUser.lastLoginTime)) {
			this.saveCurrentLogin()
		}
	},
	saveCurrentLogin(){
		return request.request({
			url:'/h5/nocloguserlogin/saveCurrentLogin',
			method: 'post',
			data: {},
		})
	}

}

